package com.example.pbj;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Misc extends ListActivity {
	
	String username;
	int idselected = 0;
	ArrayList<Post> postslist = new ArrayList<Post>();
	private static final String PHP_CAT = "http://webdev.cs.uwosh.edu/students/meyers11/PHPCat.php";
	private static final String PHP_VOTES = "http://webdev.cs.uwosh.edu/students/meyers11/PHPVotes.php";
	private static final String PHP_UP = "http://webdev.cs.uwosh.edu/students/meyers11/PHPUpvote.php";
	private static final String PHP_DOWN = "http://webdev.cs.uwosh.edu/students/meyers11/PHPDownvote.php";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_misc);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.misc, menu);
		return true;
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		new getList().execute("Misc");
		
		
		new getLoginInfo().execute();
		
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void onListItemClick(ListView list, View view, int position, long id) {
		super.onListItemClick(list, view, position, id);
		
		HashMap<String, String> hm = new HashMap<String,String>();
		
		hm = (HashMap<String, String>) list.getAdapter().getItem(position);
		
		String subject = hm.get("su");

		for(Post p : postslist){
			if(p.getSubject().equals(subject)){
				
				idselected = p.getId();
				AlertDialog.Builder alert = new AlertDialog.Builder(this);   
				
				LinearLayout lila1= new LinearLayout(this);
			    lila1.setOrientation(1); 
			    final TextView subject2 = new TextView(this); 
			    subject2.setText(subject);
			    final TextView question = new TextView(this);
			    question.setText(p.getQuestion());
			    TextView submitter = new TextView(this);
			    submitter.setText(p.getSubmitter() + "  " + p.getTime());
			    TextView upvotes = new TextView(this);
			    upvotes.setText("Upvotes: " + p.getUpvotes() + "  Downvotes: " + p.getDownvotes());
			    alert.setTitle(subject);  
			    submitter.setTextSize(22);
			    submitter.setTextColor(Color.rgb(113, 46, 128));
			    question.setTextSize(21);
			    submitter.setPadding(15,0,0,15);
			    question.setPadding(15,0,0,10);
			    upvotes.setPadding(15,0,0,5);
			    upvotes.setTextSize(20);
			    //lila1.addView(name2);
			    lila1.addView(submitter);
			    lila1.addView(question);
			    lila1.addView(upvotes);	 
			    alert.setView(lila1);

				alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
				  public void onClick(DialogInterface dialog, int whichButton) {
					  //Close
				  }
				});
				alert.setPositiveButton("Upvote", new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int whichButton) {
						    int pid = idselected;
						    new upvote().execute(Integer.toString(pid),username);
					  }
					});
				
				alert.setNeutralButton("Downvote", new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int whichButton) {
						    int pid = idselected;
						    new downvote().execute(Integer.toString(pid),username);
					  }
					});

				alert.show();
			}
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
	    // Handle item selection
	    switch (item.getItemId()) {	
	        case R.id.action_logout:
	        	new Logout().execute();
	        	Intent myIntent3 = new Intent(Misc.this, LoginActivity.class);
				startActivityForResult(myIntent3, 0);
				Misc.this.finish();
	            return true;
	        case R.id.action_submit:
	        	Intent myIntent4 = new Intent(Misc.this, Submit.class);
				startActivityForResult(myIntent4, 0);
				Misc.this.finish();
	            return true;
	        case R.id.action_mine:
	        	Intent myIntent5 = new Intent(Misc.this, MyPosts.class);
				startActivityForResult(myIntent5, 0);
				Misc.this.finish();
	            return true;
	        case R.id.action_home:
	        	Intent myIntent6 = new Intent(Misc.this, MainActivity.class);
				startActivityForResult(myIntent6, 0);
				Misc.this.finish();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	//Get Login Info
			private class getLoginInfo extends AsyncTask<Void, Void, String>{
				@Override
				protected String doInBackground(Void... nothing) {
					
					PBJDataSource mds2 = new PBJDataSource(Misc.this);
					
					mds2.open();
					
					try {
						username = mds2.getUsername();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					mds2.close();
					
					return username;
				}
				
				@Override
				protected void onPostExecute(String whatever) {
					if (username.equals("user")){
						Intent myIntent = new Intent(Misc.this, LoginActivity.class);
						startActivityForResult(myIntent, 0);
						return;
					}
					else{
						return;
					}
				}
				
			}
			
			//Logout
			private class Logout extends AsyncTask<Void, Void, String>{
				@Override
				protected String doInBackground(Void... nothing) {
					
					PBJDataSource mds2 = new PBJDataSource(Misc.this);
					
					mds2.open();
					
					try {
						mds2.logoutUser();
					} catch (Exception e) {
						e.printStackTrace();
					}
					
					mds2.close();
					
					return "";
				}
				
				@Override
				protected void onPostExecute(String whatever) {
						Intent myIntent = new Intent(Misc.this, LoginActivity.class);
						startActivityForResult(myIntent, 0);
						Misc.this.finish();
				}
				
			}
			
	
			//Search
			private class getList extends AsyncTask<String, Void, ArrayList<Post>>{
				@Override
				protected ArrayList<Post> doInBackground(String... params) {
					
					ArrayList<Post> posts = new ArrayList<Post>();
					// TODO: attempt authentication against a network service.
					String response = "";
					ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
					
					if(networkInfo != null && networkInfo.isConnected())
					{
						
						ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
						n.add(new BasicNameValuePair("cat", params[0]));
						
						HttpClient httpClient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(PHP_CAT);
						try
						{
							httppost.setEntity(new UrlEncodedFormEntity(n));
							ResponseHandler<String> respondHandler = new BasicResponseHandler();
							response = httpClient.execute(httppost, respondHandler);

							//Parse JSON Data
							int sid;
							String subject = "";
							String question = "";
							String submitter = "";
							String time = "";

							try{

								JSONArray jArray = new JSONArray(response);
								
								JSONObject json_data = null;

								for(int i = 0; i < jArray.length(); i++)
								{
									json_data = jArray.getJSONObject(i);
									
									subject = json_data.getString("subject");
									submitter = json_data.getString("submitter");
									sid = Integer.parseInt(json_data.getString("sid"));
									time = json_data.getString("time");
									question = json_data.getString("question");
														
									Post p = new Post(sid,question,subject,submitter,time,0,0);
									posts.add(p);
								}
								
							}catch(JSONException e1){
								e1.printStackTrace();
								System.out.println("HELLO search JSON error: " + e1);
							}
						}
						catch(Exception e){
							System.out.println("HELLO connection error: " + e);
							
						}
					}
					
					postslist = posts;
					return posts;
				}
				
		        @Override
		        protected void onPostExecute(ArrayList<Post> p1) {
		        	
		        	
		    		for(Post p2 : p1){
		    			new getVotes().execute(p2.getId());
		    		}
		        }
				
			}
			
			//get votes
			private class getVotes extends AsyncTask<Integer, Void, ArrayList<Post>>{
				@Override
				protected ArrayList<Post> doInBackground(Integer...params) {
				
					
					ArrayList<Post> posts = new ArrayList<Post>();
					// TODO: attempt authentication against a network service.
					String response = "";
					ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
					
					if(networkInfo != null && networkInfo.isConnected())
					{
						
						ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
						n.add(new BasicNameValuePair("id", params[0].toString()));
						
						HttpClient httpClient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(PHP_VOTES);
						try
						{
							httppost.setEntity(new UrlEncodedFormEntity(n));
							ResponseHandler<String> respondHandler = new BasicResponseHandler();
							response = httpClient.execute(httppost, respondHandler);

							//Parse JSON Data
							int upvotes;
							int downvotes;
							

							try{

								JSONArray jArray = new JSONArray(response);
								
								JSONObject json_data = null;

								for(int i = 0; i < jArray.length(); i++)
								{
									json_data = jArray.getJSONObject(i);
									
									upvotes = Integer.parseInt(json_data.getString("upvotes"));
									downvotes = Integer.parseInt(json_data.getString("downvotes"));
									for(Post p: postslist){
										if(p.getId() == params[0]){
											p.setUpvotes(upvotes);
											p.setDownvotes(downvotes);
										}
									}
								}
								
							}catch(JSONException e1){
								e1.printStackTrace();
								System.out.println("HELLO vote JSON error: " + e1);
							}
						}
						catch(Exception e){
							System.out.println("HELLO vote connection error: " + e);
							
						}
					}
				
					return postslist;
				}
				
		        @Override
		        protected void onPostExecute(ArrayList<Post> p) {

		            List<HashMap<String,String>> eList = new ArrayList<HashMap<String,String>>();
		            
		            for(int i=0;i<p.size();i++){
		            	HashMap<String, String> hm = new HashMap<String,String>();
		                hm.put("su",p.get(i).getSubject()); 
		                hm.put("vo","Upvotes: " + p.get(i).getUpvotes() + "  Downvotes: " + p.get(i).getDownvotes()); 
		                hm.put("pic", Integer.toString(R.drawable.purplebull));
		               
		                eList.add(hm);
		            }
		            
		            String[] keys = {"su","vo","pic"};
		            
		            int[] ids = {R.id.subject,R.id.votes,R.id.bullet};
		            
		            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), eList, R.layout.listview_layout, keys, ids);
		            
		           setListAdapter(adapter);

		        }
				
			}
			
			//upvote
			private class upvote extends AsyncTask<String, String, String>{
				@Override
				protected String doInBackground(String...params) {
				
					
					ArrayList<Post> posts = new ArrayList<Post>();
					// TODO: attempt authentication against a network service.
					String response = "";
					ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
					
					if(networkInfo != null && networkInfo.isConnected())
					{
						
						ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
						n.add(new BasicNameValuePair("id", params[0]));
						n.add(new BasicNameValuePair("voter", params[1]));
						
						HttpClient httpClient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(PHP_UP);
						try
						{
							httppost.setEntity(new UrlEncodedFormEntity(n));
							ResponseHandler<String> respondHandler = new BasicResponseHandler();
							response = httpClient.execute(httppost, respondHandler);
						
						}
						catch(Exception e){
							System.out.println("HELLO upvote connection error: " + e);
							
						}
					}
				
					return response;
				}
				
		        @Override
		        protected void onPostExecute(String whatever) {

		            new getList().execute("Misc");
		        }
				
			}
			
			//downvote
			private class downvote extends AsyncTask<String, String, String>{
				@Override
				protected String doInBackground(String...params) {
				
					
					ArrayList<Post> posts = new ArrayList<Post>();
					// TODO: attempt authentication against a network service.
					String response = "";
					ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
					
					if(networkInfo != null && networkInfo.isConnected())
					{
						
						ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
						n.add(new BasicNameValuePair("id", params[0]));
						n.add(new BasicNameValuePair("voter", params[1]));
						
						HttpClient httpClient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost(PHP_DOWN);
						try
						{
							httppost.setEntity(new UrlEncodedFormEntity(n));
							ResponseHandler<String> respondHandler = new BasicResponseHandler();
							response = httpClient.execute(httppost, respondHandler);
						
						}
						catch(Exception e){
							System.out.println("HELLO downvote connection error: " + e);
							
						}
					}
				
					return response;
				}
				
		        @Override
		        protected void onPostExecute(String whatever) {

		            new getList().execute("Misc");
		        }
				
			}


}
